import { reqGetCode, reqRegister, reqUserLogin, reqGetUSerInfo, reqLogOut } from '@/api'

const state = {
  code: '',
  userInfo: {}
}
const mutations = {
  GETCODE(state, code) {
    state.code = code
  },
  GETUSERINFO(state, userInfo) {
    state.userInfo = userInfo
  }
}
const actions = {
  // 获取验证码
  async getCode({ commit }, phone) {
    const res = await reqGetCode(phone)
    if (res.code == 200) {
      commit('GETCODE', res.data)
    } else {
      return Promise.reject(new Error('获取验证码失败!'))
    }
  },
  // 点击注册
  async registration({ commit }, data) {
    const res = await reqRegister(data)
    if (res.code == 200) {
      return ''
    } else {
      return Promise.reject(new Error(res.message))
    }
  },
  // 用户登录
  async userLogin({ commit }, data) {
    const res = await reqUserLogin(data)
    if (res.code == 200) {
      localStorage.setItem('token', res.data.token)
    } else {
      return Promise.reject(new Error(res.message))
    }
  },
  // 获取用户信息
  async getUserInfo({ commit }) {
    const res = await reqGetUSerInfo()
    if (res.code == 200) {
      commit('GETUSERINFO', res.data)
    }
  },
  // 退出登录
  async userLogOut({ commit, state }) {
    const res = await reqLogOut()
    if (res.code == 200) {
      state.userInfo = {}
      localStorage.removeItem('token')
    } else {
      return Promise.reject(new Error('退出失败!'))
    }
  }
}
const getters = {}

export default {
  state,
  mutations,
  actions,
  getters
}
